package com.af.security.auth.util.handler;

import com.af.service.AfRedirectService;
import com.szy.system.api.result.Result;
import com.szy.system.api.result.ResultUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author : zhenyun.su
 * @since : 2020/03/25
 * @Common : 用户资源时，若无权限访问资源时，则触发执行返回json
 * 前提： 用户已完成身份认证
 */

@Component
public class AfAccessDeniedHandler implements AccessDeniedHandler {
    private AfRedirectService redirectService;
    public AfAccessDeniedHandler(AfRedirectService redirectService) {
        this.redirectService = redirectService;
    }

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        String data = httpServletRequest.getRequestURI()+", requires authorization";
        Result<Object> result= ResultUtils.failure(HttpStatus.FORBIDDEN.value(), HttpStatus.FORBIDDEN.getReasonPhrase(), data);
        redirectService.redirectJson(httpServletResponse, result);
    }
}
